package pobidz;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;

public class Normalization {

	private List<UnprocessedColor> colors;
	
	public Normalization(List<UnprocessedColor> colors)
	{
		this.colors = colors;
	}

	public Normalization(){
		this.colors = new ArrayList<UnprocessedColor>();
	}
	
	public void addColor(UnprocessedColor color){
		this.colors.add(color);
	}
	
	
	public BufferedImage normalize(BufferedImage img, int n, boolean modifyRange)
	{
		
		double min2 = 0;
		double max2 = 255;
		int min = colors.get(0).getRed();
		int max = colors.get(0).getRed();
		int rightRange = 0;
		
		if(n==0 && modifyRange)
			rightRange=1;
		else
			rightRange = n;
		
		for (int i=0; i<colors.size(); i++)
		{
			if (min > colors.get(i).getRed())
			{
				min = colors.get(i).getRed();
			}
			if (min > colors.get(i).getGreen())
			{
				min = colors.get(i).getGreen();
			}
			if (min > colors.get(i).getBlue())
			{
				min = colors.get(i).getBlue();
			}
			
			if (max < colors.get(i).getRed())
			{
				max = colors.get(i).getRed();
			}
			if (max < colors.get(i).getGreen())
			{
				max = colors.get(i).getGreen();
			}
			if (max < colors.get(i).getBlue())
			{
				max = colors.get(i).getBlue();
			}
			
			
		}
		//System.out.println("AAAAA " + min + " " + max);
		int counter = 0;
		//System.out.println(img.getHeight()*img.getWidth() + " " + colors.size());
		for (int i=n; i<img.getHeight()-rightRange; i++)
		{
			for (int j=n; j<img.getWidth()-rightRange; j++)
			{
				
				int redVal = (int)(((max2-min2)/(max - min)) 
					* (colors.get(counter).getRed() - min) + min2);
				int greenVal = (int)(((max2 - min2)/(max-min)) 
					* (colors.get(counter).getGreen() - min) + min2);
				int blueVal = (int)(((max2 - min2)/(max-min)) 
						* (colors.get(counter++).getBlue() - min) + min2);
				
				//System.out.println(redVal + " " + greenVal + " " + blueVal);
				
				Color color = new Color (redVal, greenVal, blueVal);
				img.setRGB(j,i, color.getRGB());
				
			}
		}

	return img;
	}
	
	
	


	
	public List<UnprocessedColor> getColors() {
		return colors;
	}

	public void setColors(List<UnprocessedColor> colors) {
		this.colors = colors;
	}
	
	
}
